﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using FikriKibar.Business.Abstract;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Exceptions;
using FikriKibar.Common.Helpers;
using FikriKibar.Common.Validation.FluentValidation.Menu;
using FikriKibar.DataAccess;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.Entities.Abstract;
using FikriKibar.Entities.Composite.BaseModels;
using FikriKibar.Entities.Concrete;
using FikriKibar.Globalization;

namespace FikriKibar.Business.Concrete
{
    public class MenuManager : IMenuService
    {
        #region Global Declarations

        private readonly IMenuDal _menuDal = new EfMenuDal();

        private readonly IMenuLanguageLineDal _menuLanguageLineDal = new EfMenuLanguageLineDal();

        private readonly IMenuLanguageLineHistoryDal _menuLanguageLineHistoryDal = new EfMenuLanguageLineHistoryDal();

        private readonly IMenuHistoryDal _menuHistoryDal = new EfMenuHistoryDal();

        private readonly ILanguageDal _languageDal = new EfLanguageDal();

        private readonly ISettingDal _settingDal = new EfSettingDal();
        #endregion
        #region Methods
        public AddModel<MenuLanguageLine> Add()
        {
            return new AddModel<MenuLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void Add(AddModel<MenuLanguageLine> model)
        {
            var validator = new AddValidator(model);
            var menuLanguageLine = model.Item;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;


            var menu = new Menu
            {
                CreateDate = DateTime.Now,
                CreatedBy = fikriKibarIdentity.UserId,
                UpdatedBy = fikriKibarIdentity.UserId,
                UpdateDate = DateTime.Now

            };

            var addedMenu = _menuDal.Add(menu);

            foreach (var languageId in model.SelectedLanguageIds)
            {
                menuLanguageLine.MenuId = addedMenu.Id;
                menuLanguageLine.Menu = null;
                menuLanguageLine.LanguageId = languageId;
                menuLanguageLine.MenuName = model.Item.MenuName;
                menuLanguageLine.MenuDescription = model.Item.MenuDescription;
                menuLanguageLine.CreatedBy = fikriKibarIdentity.UserId;
                menuLanguageLine.CreateDate = DateTime.Now;
                menuLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                menuLanguageLine.UpdateDate = DateTime.Now;
                menuLanguageLine.PublishBeginDate = model.Item.PublishBeginDate;
                menuLanguageLine.PublishEndDate = model.Item.PublishEndDate;
                menuLanguageLine.DisplayOrder = addedMenu.Id;
                menuLanguageLine.IsApproved = model.Item.IsApproved;
                _menuLanguageLineDal.Add(menuLanguageLine);
            }
        }
        public UpdateModel<MenuLanguageLine> Update(int id, string language)
        {
            var menuLanguageLine = _menuLanguageLineDal.Filter(e => e.MenuId == id && e.Language.LanguageCode == language).FirstOrDefault();
            if (menuLanguageLine == null) throw new NotFoundException();
            return new UpdateModel<MenuLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                SelectedLanguageCode = language,
                ItemId = id,
                Item = menuLanguageLine
            };
        }
        public void Update(UpdateModel<MenuLanguageLine> model)
        {
            var validator = new UpdateValidator(model);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var menu = _menuDal.GetById(model.ItemId);

            var menuHistory = new MenuHistory
            {
                MenuId = menu.Id,
                CreateDate = menu.CreateDate,
                CreatedBy = menu.CreatedBy,
                UpdateDate = menu.UpdateDate,
                UpdatedBy = menu.UpdatedBy,
                IsDeleted = false
            };
            _menuHistoryDal.Add(menuHistory);


            menu.UpdateDate = DateTime.Now;
            menu.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedMenu = _menuDal.Update(menu);

            var menuLanguageLine = _menuLanguageLineDal.Filter(e => e.MenuId == model.ItemId && e.Language.LanguageCode == model.SelectedLanguageCode).FirstOrDefault();

            if (menuLanguageLine == null)
            {
                menuLanguageLine = new MenuLanguageLine
                {
                    MenuId = affectedMenu.Id,
                    Menu = null,
                    LanguageId = _languageDal.GetByCode(model.SelectedLanguageCode).Id,
                    MenuName = model.Item.MenuName,
                    MenuDescription = model.Item.MenuDescription,
                    CreatedBy = fikriKibarIdentity.UserId,
                    CreateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    UpdateDate = DateTime.Now,
                    PublishBeginDate = model.Item.PublishBeginDate,
                    PublishEndDate = model.Item.PublishEndDate,
                    DisplayOrder = affectedMenu.Id,
                    IsApproved = model.Item.IsApproved
                };
                _menuLanguageLineDal.Add(menuLanguageLine);

            }
            else
            {
                var menuLanguageLineHistory = new MenuLanguageLineHistory
                {
                    MenuLanguageLineId = menuLanguageLine.Id,
                    MenuId = menuLanguageLine.MenuId,
                    LanguageId = menuLanguageLine.LanguageId,
                    MenuName = menuLanguageLine.MenuName,
                    MenuDescription = menuLanguageLine.MenuDescription,
                    CreateDate = menuLanguageLine.CreateDate,
                    CreatedBy = menu.CreatedBy,
                    UpdateDate = menu.UpdateDate,
                    UpdatedBy = menu.UpdatedBy,
                    PublishBeginDate = menuLanguageLine.PublishBeginDate,
                    PublishEndDate = menuLanguageLine.PublishEndDate,
                    DisplayOrder = menuLanguageLine.DisplayOrder,
                    IsApproved = menuLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _menuLanguageLineHistoryDal.Add(menuLanguageLineHistory);

                menuLanguageLine.UpdateDate = DateTime.Now;
                menuLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                menuLanguageLine.MenuName = model.Item.MenuName;
                menuLanguageLine.MenuDescription = model.Item.MenuDescription;
                menuLanguageLine.PublishBeginDate = model.Item.PublishBeginDate;
                menuLanguageLine.PublishEndDate = model.Item.PublishEndDate;
                menuLanguageLine.IsApproved = model.Item.IsApproved;

                _menuLanguageLineDal.Update(menuLanguageLine);
            }




        }
        public ListModel<MenuLanguageLine> GetList(string searchTerm, string languageCode, int status, int index, int size, string idsForSort, string idsForApprove, string idsForDelete)
        {
            var model = new ListModel<MenuLanguageLine>
            {
                Paging = new Paging(),
                ItemList = new List<MenuLanguageLine>(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };

            if (idsForDelete != null)
            {
                var ids = idsForDelete;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                DeleteSelected(idList, languageCode);

            }
            model.IdsForDelete = null;


            if (idsForApprove != null)
            {
                var ids = idsForApprove;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                ApproveSelected(idList, languageCode);
            }

            model.IdsForApprove = null;

            var sortHelper = new SortHelper<MenuLanguageLine>();
            sortHelper.OrderByDescending(t => t.DisplayOrder);

            model.Paging.CurrentPageSize = size;
            model.Paging.CurrentPage = index;
            model.SelectedStatus = status;

            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.Paging.TotalItemCount = _menuLanguageLineDal.GetTotalCount(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.Paging.TotalItemCount = _menuLanguageLineDal.GetTotalCount(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }

            var pageSizeListSetting = _settingDal.GetValueByKey("PageSizeList");
            var pageSizeSettingValue = "10,25,50,100";
            if (pageSizeListSetting != null)
            {
                pageSizeSettingValue = pageSizeListSetting;
            }
            var pageSizeList = pageSizeSettingValue.Split(',').Select(t => new KeyValuePair<int, string>(t.ConvertToInt(), t)).ToList();

            pageSizeList.Insert(0, new KeyValuePair<int, string>(-1, "[" + Resources.All + "]"));
            model.Paging.PageSizeList = pageSizeList;


            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _menuLanguageLineDal.Filter(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus, sortHelper, index, size) : _menuLanguageLineDal.Filter(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _menuLanguageLineDal.Filter(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode, sortHelper, index, size) : _menuLanguageLineDal.Filter(e => e.MenuName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }


            if (idsForSort != null)
            {
                var ids = idsForSort;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                model.ItemList = SaveSort(idList, languageCode);
            }
            model.IdsForSort = null;

            model.Searched = searchTerm;
            model.SelectedLanguageCode = languageCode;

            model.Paging.CurrentPage = index;
            model.Paging.TotalPageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / size);
            return model;
        }
        public void Delete(int id, string language)
        {
            var menuLanguageLine = _menuLanguageLineDal.Filter(e => e.Language.LanguageCode == language).FirstOrDefault(e => e.Menu.Id == id);
            if (menuLanguageLine == null) return;
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var menuLanguageLineHistory = new MenuLanguageLineHistory
            {
                MenuLanguageLineId = menuLanguageLine.Id,
                MenuId = menuLanguageLine.MenuId,
                LanguageId = menuLanguageLine.LanguageId,
                MenuName = menuLanguageLine.MenuName,
                MenuDescription = menuLanguageLine.MenuDescription,
                CreateDate = menuLanguageLine.CreateDate,
                CreatedBy = menuLanguageLine.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                PublishBeginDate = menuLanguageLine.PublishBeginDate,
                PublishEndDate = menuLanguageLine.PublishEndDate,
                DisplayOrder = menuLanguageLine.DisplayOrder,
                IsApproved = menuLanguageLine.IsApproved,
                IsDeleted = true
            };
            _menuLanguageLineHistoryDal.Add(menuLanguageLineHistory);
            _menuLanguageLineDal.Delete(menuLanguageLine);

            if (_menuLanguageLineDal.Filter(e => e.MenuId == id).Any()) return;
            var menu = _menuDal.GetById(id);
            if (menu == null) return;
            var menuHistory = new MenuHistory
            {
                MenuId = menu.Id,
                CreateDate = menu.CreateDate,
                CreatedBy = menu.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                IsDeleted = true
            };
            _menuHistoryDal.Add(menuHistory);
            _menuDal.Delete(menu);
        }
        private List<MenuLanguageLine> SaveSort(IReadOnlyList<int> idList, string languageCode)
        {
            var returnedValue = new List<MenuLanguageLine>();
            for (var i = 0; i < idList.Count; i++)
            {
                var menuLanguageLine = _menuLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Menu.Id == idList[i]);

                if (menuLanguageLine == null) continue;
                var menu = _menuDal.GetById(menuLanguageLine.Menu.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

                var menuHistory = new MenuHistory
                {
                    MenuId = menu.Id,
                    CreateDate = menu.CreateDate,
                    CreatedBy = menu.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _menuHistoryDal.Add(menuHistory);


                menu.UpdatedBy = fikriKibarIdentity.UserId;
                menu.UpdateDate = DateTime.Now;
                _menuDal.Update(menu);

                var menuLanguageLineHistory = new MenuLanguageLineHistory
                {
                    MenuLanguageLineId = menuLanguageLine.Id,
                    MenuId = menuLanguageLine.MenuId,
                    LanguageId = menuLanguageLine.LanguageId,
                    MenuName = menuLanguageLine.MenuName,
                    MenuDescription = menuLanguageLine.MenuDescription,
                    CreateDate = menuLanguageLine.CreateDate,
                    CreatedBy = menuLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    PublishBeginDate = menuLanguageLine.PublishBeginDate,
                    PublishEndDate = menuLanguageLine.PublishEndDate,
                    DisplayOrder = menuLanguageLine.DisplayOrder,
                    IsApproved = menuLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _menuLanguageLineHistoryDal.Add(menuLanguageLineHistory);


                menuLanguageLine.DisplayOrder = i + 1;
                menuLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                menuLanguageLine.UpdateDate = DateTime.Now;
                menuLanguageLine.Menu = menu;
                _menuLanguageLineDal.Update(menuLanguageLine);
                returnedValue.Add(menuLanguageLine);
            }
            return returnedValue;
        }
        private void ApproveSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                var menuLanguageLine = _menuLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.Menu.Id == id);
                if (menuLanguageLine == null) continue;
                var menu = _menuDal.GetById(menuLanguageLine.Menu.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var menuHistory = new MenuHistory
                {
                    MenuId = menu.Id,
                    CreateDate = menu.CreateDate,
                    CreatedBy = menu.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _menuHistoryDal.Add(menuHistory);
                menu.UpdatedBy = fikriKibarIdentity.UserId;
                menu.UpdateDate = DateTime.Now;
                _menuDal.Update(menu);

                var menuLanguageLineHistory = new MenuLanguageLineHistory
                {
                    MenuLanguageLineId = menuLanguageLine.Id,
                    MenuId = menuLanguageLine.MenuId,
                    LanguageId = menuLanguageLine.LanguageId,
                    MenuName = menuLanguageLine.MenuName,
                    MenuDescription = menuLanguageLine.MenuDescription,
                    CreateDate = menuLanguageLine.CreateDate,
                    CreatedBy = menuLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    PublishBeginDate = menuLanguageLine.PublishBeginDate,
                    PublishEndDate = menuLanguageLine.PublishEndDate,
                    DisplayOrder = menuLanguageLine.DisplayOrder,
                    IsApproved = menuLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _menuLanguageLineHistoryDal.Add(menuLanguageLineHistory);


                menuLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                menuLanguageLine.UpdateDate = DateTime.Now;
                menuLanguageLine.IsApproved = true;
                menuLanguageLine.Menu = menu;
                _menuLanguageLineDal.Update(menuLanguageLine);

            }
        }
        private void DeleteSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                Delete(id, languageCode);
            }
        }
        #endregion
    }
}
